#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <numeric>
#include <tuple>
#include <vector>
constexpr int MaxN = 2e5 + 5;
int n, m;
int f[MaxN];
std::map<std::tuple<int, int>, bool> vis;
std::vector<std::tuple<int, int, int>> links;
int find(int x)
{
    if (f[x] != x)
    {
        f[x] = find(f[x]);
    }
    return f[x];
}
void merge(int x, int y)
{
    int fx, fy;
    fx = find(x);
    fy = find(y);
    if (fx == fy)
    {
        return;
    }
    f[fy] = fx;
}
void solve()
{
    vis.clear();
    links.clear();
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= m; i++)
    {
        int u, v, w;
        scanf("%d%d%d", &u, &v, &w);
        links.push_back({u, v, w});
        vis[{u, v}] = true;
        vis[{v, u}] = true;
    }
    if (m == 0)
    {
        printf("%d\n", n - 1);
        return;
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = i + 1; j <= n; j++)
        {
            if (vis[{i, j}])
            {
                continue;
            }
            links.push_back({i, j, j - i});
        }
    }
    std::sort(links.begin(), links.end(), [](const std::tuple<int, int, int> &x, const std::tuple<int, int, int> &y) {
        return std::get<2>(x) < std::get<2>(y);
    });
    long long answer = 0;
    std::iota(f + 1, f + 1 + n, 1);
    for (auto x : links)
    {
        if (find(std::get<0>(x)) != find(std::get<1>(x)))
        {
            answer += std::get<2>(x);
            merge(std::get<0>(x), std::get<1>(x));
        }
    }
    printf("%lld\n", answer);
}
int main()
{
    freopen("up.in", "r", stdin);
    freopen("up.out", "w", stdout);
    int t;
    scanf("%d", &t);
    for (int i = 1; i <= t; i++)
    {
        solve();
    }
    return 0;
}